package com.woniu.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
//import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("fileUpload")
public class fileUpload {
    @RequestMapping("/upload")
    public String file(MultipartFile abc, HttpServletRequest request){
        String realPath =request.getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        //获得文件名称getOriginalFilename，subString获得后缀
        String filename = abc.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        //用毫秒数来重新命名。避免并发，可以加锁
//        filename= new Date().getTime() +suffix;
        filename = UUID.randomUUID()+suffix;
        try{
            File file = new File(dir,filename);
            abc.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "index";

    }
    /**
     * 多个文件上传
     * @param abc1
     * @return
     */
    @PostMapping("uploadFiles")
    public ModelAndView uploadFile(MultipartFile[] abc1,HttpServletRequest request){
        String realPath =request.getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        //判断file数组不能为空并且长度大于0
        if (abc1 != null && abc1.length > 0) {
            //循环获取file数组中得文件
            for (int i = 0; i < abc1.length; i++) {
                MultipartFile file = abc1[i];

                //保存文件
                String filePath = FilenameUtils.concat(String.valueOf(dir), file.getOriginalFilename());
                // 转存文件
                try {
                    file.transferTo(new File(filePath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //跳转视图
        return new ModelAndView("index","msg",abc1.length+"个文件");
    }
}
